﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Windows.Forms;

namespace CLUBsInterpreter.ObjectTypes
{
	/**
	 * <summary>
	 * Describes a board object in the CLUBs environment.
	 * </summary>
	 **/
	class CLUBsBoard : CLUBsObject, Visual.IPaintable, Visual.IClickable
	{

		//public Size GridDimensions;
		public CLUBsCell[,] Grid;

		/**
		 * <summary>
		 * Default constructor creates an empty board, setting default properties.
		 * </summary>
		 **/
		public CLUBsBoard()
		{
			// Set the object identifier type
			ObjectIdentifierType = AST.IdentifierType.Board;
			// SPECIFY STANDARD ENVIRONMENT
			// Cell type variable
			LocalVariables.Declare("CellType", new CLUBsCell());
		}

		/**
		 * <see cref="CLUBsObject.CopyValueFromObject"/>
		 **/
		public override void CopyValueFromObject(CLUBsObject obj)
		{
			CLUBsBoard boardObj = (CLUBsBoard)obj;
			LocalVariables.Clear();

			foreach (KeyValuePair<string, CLUBsObject> var in boardObj.LocalVariables)
			{
				LocalVariables.Add(var.Key, var.Value);
				LocalVariables[var.Key].CopyValueFromObject(var.Value);
			}
		}

		public void Paint(object sender, PaintEventArgs args)
		{
			Graphics g = args.Graphics;
			Rectangle clip = args.ClipRectangle;
			Pen p = new Pen(Color.Black, 1.0f);
			p.DashStyle = System.Drawing.Drawing2D.DashStyle.Solid;
			Brush bg = new SolidBrush(Color.White);
			g.Clear(Color.White);
			g.DrawRectangle(p, 0, 0, clip.Width - 1, clip.Height - 1);

			PaintEventArgs subArgs;

			int cellsX = Grid.GetUpperBound(0) + 1;
			int cellsY = Grid.GetUpperBound(1) + 1;
			int cellWidth = clip.Width / cellsX;
			int cellHeight = clip.Height / cellsY;

			for (int x = 0; x < cellsX; x++)
			{
				for (int y = 0; y < cellsY; y++)
				{
					subArgs = new PaintEventArgs(g, new Rectangle(x * cellWidth, y * cellHeight, cellWidth, cellHeight));
					Grid[x, y].Paint(sender, subArgs);
				}
			}

		}

		public void OnClick(object sender, MouseEventArgs args)
		{
			if (StandardEnvironment.Instance != null && StandardEnvironment.Instance.SelectingCell)
			{
				// Find click cell coords
				int numCellsX = Grid.GetUpperBound(0) + 1;
				int numCellsY = Grid.GetUpperBound(1) + 1;
				int cellWidth = Interpreter.WINDOW_WIDTH / numCellsX;
				int cellHeight = Interpreter.WINDOW_HEIGHT / numCellsY;
				int cellX = args.X / cellWidth;
				int cellY = args.Y / cellHeight;

				if (cellX < 0 || cellX >= numCellsX ||
					cellY < 0 || cellY >= numCellsY)
				{
					return;
				}

				// Check if cell is eligible
				if (Grid[cellX, cellY].Selectable)
				{
					// If so, "return" cell
					StandardEnvironment.Instance.SelectedCell = Grid[cellX, cellY];
					StandardEnvironment.Instance.SelectingCell = false;
				}
			}
		}

	}
}
